package com.simple.core.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.simple.core.entity.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;
import java.util.Objects;

import static org.springframework.data.domain.Sort.Direction.DESC;

/**
 * 分页参数
 */

@Slf4j
@Data
@ApiModel(description = "分页表单参数")
public class PageRequestDto implements Serializable {
    private static final long serialVersionUID = 1L;

    public static final Sort.Order DEFAULT_SORT_BY_ID_DESC = new Sort.Order(DESC, BaseEntity.Fields.id);


    /**
     * 每页显示条数，默认 10
     */
    @ApiModelProperty("每页显示条数，默认 10")
    private int size = 10;

    /**
     * 当前页
     */
    @ApiModelProperty("当前页")
    private int current = 1;


    @JsonIgnore
    @ApiModelProperty(hidden = true)
    public int getOffset() {
        return (current - 1) * size;
    }

    @JsonIgnore
    @ApiModelProperty(hidden = true)
    public int getLimit() {
        return size;
    }

    @JsonIgnore
    // 这里 @ApiModelProperty(hidden = true) 不生效
    // 可能是版本问题 有时间再debug吧 不用get开头就没问题
    @ApiModelProperty(hidden = true)
    public Pageable buildPageable() {
        if (this.size > 1000) {
            log.warn("[分页]- oversize - {}", this.size);
        }
        return PageRequest.of(Math.max(getCurrent() - 1, 0), getSize(), Sort.by(DEFAULT_SORT_BY_ID_DESC));
    }

    @JsonIgnore
    @ApiModelProperty(hidden = true)
    public Pageable buildPageable(Sort sort) {
        if (this.size > 1000) {
            log.warn("[分页]- oversize - {}", this.size);
        }
        sort = Objects.isNull(sort) ? Sort.by(DEFAULT_SORT_BY_ID_DESC) : sort;
        return PageRequest.of(Math.max(getCurrent() - 1, 0), getSize(), sort);
    }
}
